package gw.com.android.ui;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.KeyEvent;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.android.rxbus.SimpleObserver;
import com.gwtsz.chart.output.utils.GTTKDataManager;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.greendao.NotifyDataHelper;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.AdsConfigPresenter;
import gw.com.android.presenter.AdsData;
import gw.com.android.presenter.FMPresenter;
import gw.com.android.presenter.HomePresenter;
import gw.com.android.presenter.LoginPresenter;
import gw.com.android.presenter.NoviceWelfarePresenter;
import gw.com.android.presenter.PresenterImpl;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.dialog.AdsPopWindow;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.dialog.PopupDoubleBtnDialog;
import gw.com.android.ui.home.HomeFragment;
import gw.com.android.ui.me.MineFragment;
import gw.com.android.ui.news.MainNewsFragment;
import gw.com.android.ui.onlive.MainLiveFragment;
import gw.com.android.ui.positions.MainTradeFragment;
import gw.com.android.ui.quote2.NewQuoteFragment;
import gw.com.android.ui.trade.Fragment.LoginGuideFragment;
import gw.com.android.ui.views.MainBottomTabView;
import gw.com.android.upgrade.UpdateDialog;
import gw.com.android.upgrade.UpgradeHelper;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import www.com.library.app.AppActivities;
import www.com.library.app.FragmentsManagerUtil;
import www.com.library.app.Logger;
import www.com.library.app.ObjectSessionStore;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.util.NetworkMonitor;
import www.com.library.view.RecyclerClickListener;

/**
 * 主面板界面
 */
public class MainActivity extends BaseActivity implements PresenterImpl {

    @BindView(R.id.bottom_tab)
    MainBottomTabView mHomeTabView = null; // 底部tab控件

    private NewQuoteFragment mQuoteFragment;
    private MainTradeFragment mTradeFragment;
    private PushMsgTabFragment mNewFragment;
    private MineFragment mMeFragment;
    private HomeFragment mHomeFragment;
    private WebFragment mHomeUrlFragment;
    private MainLiveFragment mLiveFragment;
    private WebFragment calendarFragment;
    private WebFragment noticeFragment;
    private WebFragment immediateFragment;

    private PopupDoubleBtnDialog mExitDialog;
    private LoginPresenter mPresenter;
    private HomePresenter homePresenter;
    private AdsData tabAd;
    private int mainNum;

    public MainActivity() {
        super();
        Logger.e("MainActivity is new ");
        MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(this.getClass().getSimpleName() + GTSDataListener.mainNum);
        if (mainActivity != null) {
            Logger.e("MainActivity is finish ");
            mainActivity.finish();
        }
        mExitDialog = null;
        mainNum = ++GTSDataListener.mainNum;
        ObjectSessionStore.setObject(this.getClass().getSimpleName() + mainNum, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GTConfig.instance().setBooleanValue(GTConfig.PREF_USER_HELP, true);
        NoviceWelfarePresenter.getInstance().onMainActivityStarted();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_main;
    }

    @Override
    protected void initLayoutView() {
        if (null != getIntent() && getIntent().getExtras() != null) {
            GTConfig.instance().hasNotify = false;
            mCurrentTag = getIntent().getStringExtra("mCurTag");
            int where = getIntent().getIntExtra("where", 0);
            if (where == AppContances.FROM_LANGUAGE_ACTIVITY) {
                ActivityManager.showSettingActivity(this, ConfigType.SYSTEM_SETTING_TAG,
                        AppMain.getAppString(R.string.main_menu_item_my), AppMain.getAppString(R.string.system_set_up));
            } else if (where == 0 || where == AppContances.TYPE_FORM_NOTIFY) {
                dispatchFromNotify(where);
            }
        }
        GTConfig.instance().hasShowMain = true;
    }

    private void dispatchFromNotify(int where) {
        mPresenter = new LoginPresenter(this);
        mPresenter.setPresenterImpl(this);
        if (!NetworkMonitor.hasNetWork()) {
            AppTerminal.instance().setNetWorkState(AppContances.NET_WORK_NO_TYPE, false);
        }
        mPresenter.autoLogin();
        GTConfig.instance().hasNotify = true;
        UpgradeHelper.getInstance().start();//版本检查
        if (where == AppContances.TYPE_FORM_NOTIFY) {  //从通知栏进入
            if (getIntent().getBooleanExtra("isOpenApiPush", false)) {
                String extend = getIntent().getStringExtra("extend");
                ActivityManager.showBulletinDetailActivityOpenApi(this,
                        AppMain.getAppString(R.string.system_notice_detail),
                        String.valueOf(getIntent().getIntExtra("mDataId", 0)),
                        getIntent().getStringExtra("type"),
                        getIntent().getStringExtra("language"),
                        getIntent().getStringExtra("url"), extend);
            } else {
                ActivityManager.showBulletinDetailActivity(this,
                        AppMain.getAppString(R.string.system_notice_detail),
                        getIntent().getIntExtra("mDataId", 0),
                        getIntent().getStringExtra("type"),
                        getIntent().getStringExtra("language"),
                        getIntent().getStringExtra("title"));
            }
        }
    }

    @Override
    protected void initViewData() {
        homePresenter = new HomePresenter(MainActivity.this);
        homeTabClickListener();
        setTabFragment(mCurrentTag, "");
        refreshHomeAds();
    }

    @Override
    public void registerRxBus() {
        super.registerRxBus();
        Disposable progressRegister = RxBus.getInstance().register(GTSConst.REPLY_STATUS_PROGRESS, Boolean.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {

                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Boolean isVissible) throws Exception {
                        onProgressVisible(isVissible);
                    }
                });
        bindSubscription(progressRegister);

        Disposable adsPopRegister = RxBus.getInstance().register(GTSConst.REPLY_RFRESH_ADS, String.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {

                    @Override
                    public void accept(@NonNull String jsonStr) {
                        refreshHomeAds();
                    }
                });
        bindSubscription(adsPopRegister);

        Disposable tabAdRegister = RxBus.getInstance().register(GTSConst.REPLY_SWITCH_LOGIN_TYPE, Integer.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(@NonNull Integer state) {
                        refreshTabAds();
                    }
                });
        bindSubscription(tabAdRegister);

        Disposable quoteAllRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_ALLLIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (mCurrentFragment != null && isResumed) {
                            mCurrentFragment.onSendQuote();
                        }
                    }
                });
        bindSubscription(quoteAllRegister);

        Disposable positionListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_POSTION_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (mCurrentFragment != null && isResumed) {
                            mCurrentFragment.onSendQuote();
                        }
                    }
                });
        bindSubscription(positionListRegister);

        Disposable orderListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_ORDER_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (mCurrentFragment != null && isResumed) {
                            mCurrentFragment.onSendQuote();
                        }
                    }
                });
        bindSubscription(orderListRegister);

        Disposable noticeRegister = RxBus.getInstance().register("notification_data_update", Boolean.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Boolean isConnection) throws Exception {
                        loadRedPoint();
                    }
                });
        bindSubscription(noticeRegister);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (GTConfig.instance().mHasKickOut) {
            PopupConfirmDialog.getKickOut(MainActivity.this, GTSDataListener.instance().mContent);
        }
        if (!GTConfig.instance().loadedAdsPop) {
            homePresenter.dealPopAdsData();
        }
        if (mCurrentFragment != null && isResumed) {
            mCurrentFragment.onSendQuote();
        }
    }

    @Override
    public void onRequestSuc(Object result) {
    }

    @Override
    public void onRequestFail(int failCode) {
    }

    private void loadRedPoint() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                e.onNext(NotifyDataHelper.getUnreadCount());
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SimpleObserver<Integer>() {
            @Override
            public void onNext(Integer result) {
                refreshRedPoint(result);
            }
        });
    }

    private void refreshRedPoint(int count) {
        if (mHomeTabView != null) {
            mHomeTabView.refreshRedPoint(count);
        }
        if (mMeFragment != null) {
            mMeFragment.refreshRedPoint(count);
        }
    }

    public void homeTabClickListener() {
        mHomeTabView.setRecyclerClickListener(new RecyclerClickListener() {

            /**
             * 2018年12月17日 10:45:43 重构部分代码，凡是超过4行的if分支，全部整理成单独方法，免得看的乱
             */
            @Override
            public void onClick(int position, DataItemDetail itemDetail) {
                String tabName = itemDetail.getString(ConfigType.CONFIG_TYPE_KEY_TAG);
                if (tabName.equals(ConfigType.TAB_QUOTE_TAG)) {//行情
                    dispatchQuote();
                } else if (tabName.equals(ConfigType.TAB_TRADE_TAG)) {//交易
                    if (dispatchDeal()) {
                        return;
                    }
                } else if (tabName.equals(ConfigType.TAB_HOME_TAG)) {//首页
                    dispatchHome(itemDetail);
                } else if (tabName.equals(ConfigType.TAB_NEWS_TAG)) {//
                    dispatchNews();
                } else if (tabName.equals(ConfigType.TAB_MYSELF_TAG)) {//我的
                    dispatchMyself();
                } else if (tabName.equals(ConfigType.TAB_ONLIVE_TAG)) {
                    dispatchOnLive();
                } else if (tabName.equals(ConfigType.TAB_CALENDAR_TAG)) {
                    NetworkMonitor.hasNetWork();
                    showCalendarFragment();
                } else if (tabName.equals(ConfigType.TAB_NOTICE_TAG)) {//直播
                    NetworkMonitor.hasNetWork();
                    showNoticeFragment();
                } else if (tabName.equals(ConfigType.TAB_IMMEDIATE_TAG)) {//直播
                    NetworkMonitor.hasNetWork();
                    showImmediateFragment();
                }
                mHomeTabView.setSelectPositon(position);
            }

        });
    }

    private void dispatchQuote() {//行情
        showQuoteFragment();
        MobclickEventUtlis.MobclickEventByAccountType(MainActivity.this, "quote");
        PackStatis.getToService(PackStatis.EventAction.CLICKTABBAR.getValue(), PackStatis.EventCategory.MAIN.getValue(), "Market", "行情");
        // 未连上网络时,气泡提示
        if (NetworkMonitor.hasNetWork()) {
            ServerConnnectUtil.instance().hasReConnectServer();
        }
    }

    private boolean dispatchDeal() {//交易
        if (handleTabAds()) {
            return true;
        }
        // 游客登录时弹出提示
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
            showLoginGuideFragment();
        } else {
            if (!DataManager.instance().hasAccount()) {
                final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(MainActivity.this, "", ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1021));
                dialog.show();
                return true;
            }
            PackStatis.getToService(PackStatis.EventAction.CLICKTABBAR.getValue(), PackStatis.EventCategory.MAIN.getValue(), "trade", "交易");
            showTradeFragment("");
            MobclickEventUtlis.MobclickEventByAccountType(MainActivity.this, "trade");
            // 未连上网络时,气泡提示
            if (NetworkMonitor.hasNetWork()) {
                ServerConnnectUtil.instance().hasReConnectServer();
            }
        }
        return false;
    }

    private void dispatchHome(DataItemDetail itemDetail) {//首页
        if (mCurrentTag.equals(ConfigType.TAB_HOME_TAG)) {
            if (mHomeFragment != null) {
                if (mHomeFragment.isWholeNewsMode()) {
                    Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                    if (vib != null) {
                        vib.vibrate(50);
                    }
                    if (mHomeTabView != null) {
                        mHomeTabView.rotateHomeIcon();
                    }
                }
                mHomeFragment.onHomeTabClicked();
            }
            return;
        }
        // 未连上网络时,气泡提示
        if (NetworkMonitor.hasNetWork()) {
            ServerConnnectUtil.instance().hasReConnectServer();
        }
        PackStatis.getToService(PackStatis.EventAction.CLICKTABBAR.getValue(), PackStatis.EventCategory.MAIN.getValue(), "home", "首页");
        MobclickEventUtlis.MobclickEventByAccountType(MainActivity.this, "home");
        //首页
        showHomeFragment(itemDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
    }

    private void dispatchNews() {//远古代码，看不懂
        // 未连上网络时,气泡提示
        NetworkMonitor.hasNetWork();
        PackStatis.getToService(PackStatis.EventAction.CLICKTABBAR.getValue(), PackStatis.EventCategory.MAIN.getValue(), "new", "new");
        MobclickEventUtlis.MobclickEventByAccountType(MainActivity.this, "new");
        showNewFragment();
    }

    private void dispatchMyself() {//我的
        // 未连上网络时,气泡提示
        NetworkMonitor.hasNetWork();
        PackStatis.getToService(PackStatis.EventAction.CLICKTABBAR.getValue(), PackStatis.EventCategory.MAIN.getValue(), "me", "我的");
        MobclickEventUtlis.MobclickEventByAccountType(MainActivity.this, "me");
        showMeFragment();
    }

    private void dispatchOnLive() {
        NetworkMonitor.hasNetWork();//直播
        PackStatis.getToService("clickCircle", PackStatis.EventCategory.MAIN.getValue(), "broadcast", "broadcast");
        MobclickEventUtlis.MobclickEventByAccountType(MainActivity.this, "broadcast");
        showOnliveFragment(-1);
    }

    /**
     * 根据当前tag显示fragment
     */
    public void setTabFragment(String tag, String subTag) {
        if (null == tag || tag.equals("")) {
            tag = ConfigType.TAB_QUOTE_TAG;
        }
        mCurrentTag = tag;
        DataItemDetail itemDetail = mHomeTabView.setSelectStr(mCurrentTag);
        if (mCurrentTag.equals(ConfigType.TAB_QUOTE_TAG)) {
            mHomeTabView.onNightMode(GTConfig.instance().isQuoteChartNight());
        } else {
            mHomeTabView.onNightMode(false);
        }
        if (mCurrentTag.equals(ConfigType.TAB_QUOTE_TAG)) {
            showQuoteFragment();
        } else if (mCurrentTag.equals(ConfigType.TAB_TRADE_TAG)) {
            if (!handleTabAds()) {
                if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
                    showLoginGuideFragment();
                } else {
                    showTradeFragment(subTag);
                }
            }
        } else if (mCurrentTag.equals(ConfigType.TAB_HOME_TAG)) {
            showHomeFragment(itemDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
        } else if (mCurrentTag.equals(ConfigType.TAB_NEWS_TAG)) {
            showNewFragment();
        } else if (mCurrentTag.equals(ConfigType.TAB_MYSELF_TAG)) {
            showMeFragment();
        } else if (mCurrentTag.equals(ConfigType.TAB_ONLIVE_TAG)) {
            if ("1".equals(subTag)) { // 解盘
                showOnliveFragment(1);
            } else if ("0".equals(subTag)) { // 晒单
                showOnliveFragment(0);
            } else {
                showOnliveFragment(-1); // 默认页
            }
        } else if (mCurrentTag.equals(ConfigType.TAB_CALENDAR_TAG)) {
            showCalendarFragment();
        } else if (mCurrentTag.equals(ConfigType.TAB_NOTICE_TAG)) {
            showNoticeFragment();
        } else if (mCurrentTag.equals(ConfigType.TAB_IMMEDIATE_TAG)) {
            showImmediateFragment();
        }
    }

    /**
     * 删除所有的fragment
     */
    public void removeAllFragment(boolean isAll, boolean isDelQuote) {
        mFragmentTransaction = mFragmentManager.beginTransaction();
        if (null != mHomeFragment) {
            mFragmentTransaction.remove(mHomeFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_HOME_TAG);
            mHomeFragment = null;
        }
        if (isDelQuote) {
            if (null != mQuoteFragment) {
                mFragmentTransaction.remove(mQuoteFragment);
                FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_QUOTE_TAG);
                mQuoteFragment = null;
            }
        }
        if (null != mHomeUrlFragment) {
            mFragmentTransaction.remove(mHomeUrlFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_HOME_TAG);
            mHomeUrlFragment = null;
        }
        if (null != mTradeFragment) {
            mFragmentTransaction.remove(mTradeFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_TRADE_TAG);
            mTradeFragment = null;
        }
        if (null != mNewFragment) {
            mFragmentTransaction.remove(mNewFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_NEWS_TAG);
            mNewFragment = null;
        }
        if (null != mLiveFragment) {
            mFragmentTransaction.remove(mLiveFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_ONLIVE_TAG);
            mLiveFragment = null;
        }
        if (null != calendarFragment) {
            mFragmentTransaction.remove(calendarFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_CALENDAR_TAG);
            calendarFragment = null;
        }
        if (null != noticeFragment) {
            mFragmentTransaction.remove(noticeFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_NOTICE_TAG);
            noticeFragment = null;
        }
        if (null != immediateFragment) {
            mFragmentTransaction.remove(immediateFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_IMMEDIATE_TAG);
            immediateFragment = null;
        }
        if (null != mMeFragment) {
            mFragmentTransaction.remove(mMeFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_MYSELF_TAG);
            mMeFragment = null;
        }
        mFragmentTransaction.commitAllowingStateLoss();
    }

    public void removeQuoteFragment() {
        mFragmentTransaction = mFragmentManager.beginTransaction();
        if (null != mQuoteFragment) {
            mFragmentTransaction.remove(mQuoteFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_QUOTE_TAG);
            mQuoteFragment = null;
        }
        mFragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 删除所有的fragment,除嵌套首页
     */
    public void removeFragment() {
        mFragmentTransaction = mFragmentManager.beginTransaction();
        if (null != mHomeFragment) {
            mFragmentTransaction.remove(mHomeFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_HOME_TAG);
            mHomeFragment = null;
        }
        if (null != mQuoteFragment) {
            mFragmentTransaction.remove(mQuoteFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_QUOTE_TAG);
            mQuoteFragment = null;
        }
        if (null != mTradeFragment) {
            mFragmentTransaction.remove(mTradeFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_TRADE_TAG);
            mTradeFragment = null;
        }
        if (null != mNewFragment) {
            mFragmentTransaction.remove(mNewFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_NEWS_TAG);
            mNewFragment = null;
        }
        if (null != mLiveFragment) {
            mFragmentTransaction.remove(mLiveFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_ONLIVE_TAG);
            mLiveFragment = null;
        }
        if (null != mMeFragment) {
            mFragmentTransaction.remove(mMeFragment);
            FragmentsManagerUtil.instance().removeFragmentbyTag(this, ConfigType.TAB_MYSELF_TAG);
            mMeFragment = null;
        }

        mFragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 刷新首页网页
     */
    public void refreshHomeWeb() {
        if (mHomeUrlFragment != null) {
            mHomeUrlFragment.refreshView();
        }
    }

    private boolean handleTabAds() {
        if (tabAd != null && !tabAd.adPics.isEmpty()) {
            AdsData.PicData picData = tabAd.adPics.get(0);
            if (picData != null) {
                DataItemDetail mItem = new DataItemDetail();
                mItem.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, picData.title);
                mItem.setStringValue(ConfigType.CONFIG_TYPE_TYPE_URL_TAG, picData.link);
                ActivityManager.showWebPageActivity(this, picData.title, picData.link, true);
                if (tabAd.adPics.size() > 1) {
                    final AdsData.PicData popAd = tabAd.adPics.get(1);
                    if (popAd != null) {
                        AppMain.getApp().getHandler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Activity activity = AppActivities.getSingleton().currentActivity();
                                if (activity != null && !activity.isFinishing()) {
                                    AdsPopWindow popWindow = new AdsPopWindow(activity);
                                    popWindow.setImageView(popAd);
                                    popWindow.setScale();
                                    popWindow.show();
                                }
                            }
                        }, 2000);
                    }
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 展示行情界面
     */
    public void showQuoteFragment() {
        mCurrentTag = ConfigType.TAB_QUOTE_TAG;
        mQuoteFragment = (NewQuoteFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
        if (null == mQuoteFragment) {
            mQuoteFragment = new NewQuoteFragment();
            Bundle bundle = new Bundle();
            mQuoteFragment.setArguments(bundle);
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, mQuoteFragment, mCurrentTag);
        }
        showFragment(mQuoteFragment);
    }

    /**
     * 展示首页
     */
    public void showHomeFragment(String title) {
        mCurrentTag = ConfigType.TAB_HOME_TAG;
        if (ConfigUtil.instance().homeFucType() == 1) {
            mHomeFragment = (HomeFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
            if (null == mHomeFragment) {
                mHomeFragment = new HomeFragment();
                FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, mHomeFragment, mCurrentTag);
            }
            AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
            showFragment(mHomeFragment);
        } else {
            mHomeUrlFragment = (WebFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
            if (null == mHomeUrlFragment) {
                mHomeUrlFragment = WebFragment.newInstance();
                Bundle bundle = new Bundle();
                bundle.putString(ConfigType.CONFIG_TYPE_KEY_TAG, ConfigType.TAB_HOME_TAG);
                bundle.putString(ConfigType.CONFIG_TYPE_TITLE_TAG, title);
                bundle.putBoolean("hasTitle", false);
                bundle.putString("url", ConfigUtil.instance().getUrlPath(ConfigType.TAB_HOME_TAG));
                mHomeUrlFragment.setArguments(bundle);
                FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, mHomeUrlFragment, mCurrentTag);
            }
            AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
            showFragment(mHomeUrlFragment);
        }
    }

    /**
     * 展示直播
     */
    public void showOnliveFragment(int page) {
        FMPresenter.getInstance().pause();
        mCurrentTag = ConfigType.TAB_ONLIVE_TAG;
        mLiveFragment = (MainLiveFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
        if (null == mLiveFragment) {
            mLiveFragment = new MainLiveFragment();
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, mLiveFragment, mCurrentTag);
        }
        mLiveFragment.setPage(page);
        showFragment(mLiveFragment);
    }

    /**
     * 展示交易界面
     */
    public void showTradeFragment(String tag) {
        mCurrentTag = ConfigType.TAB_TRADE_TAG;
        mTradeFragment = (MainTradeFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
        if (null == mTradeFragment) {
            mTradeFragment = MainTradeFragment.newInstance();
            if (tag != null && !tag.equals("")) {
                Bundle bundle = new Bundle();
                bundle.putString("mCurTag", tag);
                mTradeFragment.setArguments(bundle);
            }
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, mTradeFragment, mCurrentTag);
        } else {
            if (tag != null && !tag.equals("")) {
                mTradeFragment.showFragment(tag);
            }
        }
        showFragment(mTradeFragment);
    }

    private void showLoginGuideFragment() {
        mCurrentTag = ConfigType.TAB_UNLOGIN_TAG;
        LoginGuideFragment mLoginGuideFragment = (LoginGuideFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
        if (null == mLoginGuideFragment) {
            mLoginGuideFragment = new LoginGuideFragment();
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, mLoginGuideFragment, mCurrentTag);
        }
        showFragment(mLoginGuideFragment);
    }

    /**
     * 展示资讯界面
     */
    public void showNewFragment() {
        mCurrentTag = ConfigType.TAB_NEWS_TAG;
        mNewFragment = FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);

        if (null == mNewFragment) {
            mNewFragment = MainNewsFragment.newInstance("");
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, mNewFragment, mCurrentTag);
        }
        showFragment(mNewFragment);
    }

    public void showMeFragment() {
        mCurrentTag = ConfigType.TAB_MYSELF_TAG;
        mMeFragment = (MineFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
        if (null == mMeFragment) {
            mMeFragment = new MineFragment();
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, mMeFragment, mCurrentTag);
        }
        showFragment(mMeFragment);
    }

    /**
     * 显示财经日历
     */
    public void showCalendarFragment() {
        mCurrentTag = ConfigType.TAB_CALENDAR_TAG;
        calendarFragment = (WebFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
        if (null == calendarFragment) {
            calendarFragment = WebFragment.newInstance();
            Bundle bundle = new Bundle();
            bundle.putString(ConfigType.CONFIG_TYPE_KEY_TAG, ConfigType.TAB_CALENDAR_TAG);
            bundle.putBoolean("hasTitle", false);
            bundle.putString("url", ConfigUtil.instance().getUrlPath(ConfigType.TAB_CALENDAR_TAG));
            calendarFragment.setArguments(bundle);
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, calendarFragment, mCurrentTag);
        }
        showFragment(calendarFragment);
    }

    /**
     * 显示公告
     */
    public void showNoticeFragment() {
        mCurrentTag = ConfigType.TAB_NOTICE_TAG;
        noticeFragment = (WebFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
        if (null == noticeFragment) {
            noticeFragment = WebFragment.newInstance();
            Bundle bundle = new Bundle();
            bundle.putString(ConfigType.CONFIG_TYPE_KEY_TAG, ConfigType.TAB_NOTICE_TAG);
            bundle.putBoolean("hasTitle", false);
            bundle.putString("url", ConfigUtil.instance().getUrlPath(ConfigType.TAB_NOTICE_TAG));
            noticeFragment.setArguments(bundle);
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, noticeFragment, mCurrentTag);
        }
        showFragment(noticeFragment);
    }

    /**
     * 显示即时报价
     */
    public void showImmediateFragment() {
        mCurrentTag = ConfigType.TAB_IMMEDIATE_TAG;
        immediateFragment = (WebFragment) FragmentsManagerUtil.instance().getFragmentbyTag(MainActivity.this, mCurrentTag);
        if (null == immediateFragment) {
            immediateFragment = WebFragment.newInstance();
            Bundle bundle = new Bundle();
            bundle.putString(ConfigType.CONFIG_TYPE_KEY_TAG, ConfigType.TAB_IMMEDIATE_TAG);
            bundle.putBoolean("hasTitle", false);
            bundle.putString("url", ConfigUtil.instance().getUrlPath(ConfigType.TAB_IMMEDIATE_TAG));
            immediateFragment.setArguments(bundle);
            FragmentsManagerUtil.instance().addPushMsgTabFragment(MainActivity.this, immediateFragment, mCurrentTag);
        }
        showFragment(immediateFragment);
    }

    /**
     * 刷新首页广告
     */
    public void refreshHomeAds() {
        if (!GTConfig.instance().loadedAdsPop) {
            homePresenter.dealPopAdsData();
        }
        if (null != mHomeFragment) {
            mHomeFragment.refreshHomeAds();
        }
        if (mMeFragment != null) {
            mMeFragment.refreshMeAds();
        }
        refreshTabAds();
    }

    public void refreshTabAds() {
        if (mHomeTabView != null) {
            tabAd = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_TAB_TRADE);
            mHomeTabView.refreshTabAd(tabAd);
        }
    }

    @Override
    protected void onSendQuote() {
        //主面板根据每个版本情况发送订阅信息
    }

    @Override
    public void quoteServerNotice(Boolean isConntion) {
        Logger.e("mainActivity quoteServerNotice " + isConntion);
        //当前界面不在最前面不处理逻辑
        if (null != mQuoteFragment) {
            mQuoteFragment.quoteServerNotice(isConntion);
        }
        if (null != mTradeFragment) {
            mTradeFragment.quoteServerNotice(isConntion);
        }
    }

    @Override
    public void tradeServerNotice(Boolean isConntion) {
        super.tradeServerNotice(isConntion);
        Logger.e("mainActivity tradeServerNotice " + isConntion);
        if (null != mQuoteFragment) {
            mQuoteFragment.tradeServerNotice(isConntion);
        }
    }

    public void onProgressVisible(Boolean isVisible) {
        if (null != mTradeFragment) {
            mTradeFragment.onProgressVisible(isVisible);
        }
    }

    public void switchHomeTabIcon(boolean refreshMode) {
        if (mHomeTabView != null) {
            mHomeTabView.switchHomeTabIcon(refreshMode);
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (null != mPresenter) {
            mPresenter.setPresenterImpl(null);
            mPresenter.clear();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != UpdateDialog.instance()) {
            UpdateDialog.instance().dismiss();
        }
        if (null != mPresenter) {
            mPresenter.setPresenterImpl(null);
            mPresenter.clear();
        }
        ObjectSessionStore.removeObject(this.getClass().getSimpleName() + mainNum);
        FMPresenter.getInstance().release();
        if (Util.isOnMainThread() && !this.isFinishing()) {
            Glide.with(this).pauseRequests();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Logger.e("onKeyDown = " + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (ConfigType.TAB_ONLIVE_TAG.equals(mCurrentTag)) {
                if (mLiveFragment != null && mLiveFragment.onBackPressed()) {
                    return true;
                }
            }

            if (mExitDialog == null)
                mExitDialog = PopupDoubleBtnDialog.getAppExit(this);

            if (!mExitDialog.isShowing())
                mExitDialog.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppContances.REQUEST_CHART_CODE) {
            Logger.e("图表界面返回到主面板 ");
            GTTKDataManager.instance().clearTimeData();
            GTTKDataManager.instance().clearKData();
            GTTKDataManager.instance().clearIndictor();
            AppTerminal.instance().clearAllChartCache();
        } else if (resultCode == AppContances.RESULT_CODE) {
            //晒单成功返回到首页逻辑处理
            if (null != mHomeFragment) {
                mHomeFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    public void onNightMode() {
        mHomeTabView.onNightMode(GTConfig.instance().isQuoteChartNight());
    }

}
